package com.example.online_forum.services.impl;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.dao.ArticleReplyMapper;
import com.example.online_forum.exception.AppException;
import com.example.online_forum.model.ArticleReply;
import com.example.online_forum.services.IArticleReplyService;
import com.example.online_forum.services.IArticleService;
import com.example.online_forum.untils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private IArticleService articleService;

    /**
     * 创建回复
     * @param articleReply
     */
    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setDeleteState((byte)0);
        articleReply.setState((byte)0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row!= 1){
            log.warn(ResultCode.ERROR_SERVICES.toString() + " articleReply + create");
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子表中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复成功 + article id = " +articleReply.getArticleId() + ",userid id = " +articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
         if(articleId == null ||  articleId <= 0){
             // 打印日志
             log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
             // 抛出异常
             throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
         //调用dao
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
         return result;
    }
}
